//
//  HXRequest.m
//  qwm
//
//  Created by kevin on 2023/3/31.
//

#import "HXRequest.h"
#import "YTKNetworkConfig.h"
 
@implementation HXRequest
 
- (instancetype)init
{
    self = [super init];
    if (self) {
//        [YTKNetworkConfig sharedConfig].debugLogEnabled = YES;  //开启Debug模式
        
        self.verifyJSONFormat = NO;
    }
    return self;
}
 
- (NSString *)baseUrl {
    
    return QWM_BASE_API_URL;
}
 
- (NSTimeInterval)requestTimeoutInterval {
    return 30;
}
 
- (id)jsonValidator {
    if (self.verifyJSONFormat) {
        return @{
                 @"data": [NSObject class],
                 @"code": [NSNumber class],
                 @"msg": [NSString class]
                 };
    }else
    {
        return nil;
    }
}
 
- (void)startWithCompletionBlockWithSuccess:(nullable HXRequestCompletionBlock)success
                                    failure:(nullable HXRequestCompletionFailureBlock)failure
{
    //网络判断
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    if (reach.currentReachabilityStatus == NotReachable) {
        [SWHUDUtil hideHudViewWithFailureMessage:@"网络不给力，请检查网络设置。"];
        return;
    }
    
    [super startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        
        NSDictionary *result = [request responseJSONObject];
        
        BOOL isSuccess = YES;
        
        //校验格式
        if (self.verifyJSONFormat) {
            isSuccess = [[result objectForKey:@"code"] intValue] == 0;
        }
        
        success(request,result,isSuccess);
        
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        
        NSLog(@"%@",self.description);
 
        failure(request,[self errorInfo:request]);
    }];
}
 
- (NSString *)description {
    //打印自己认为重要的信息
    return [NSString stringWithFormat:@"%@ \nstatusCode:%ld\nresponseJSONObject:\n%@",super.description,self.responseStatusCode,self.responseJSONObject];
}
 
- (NSString *)errorInfo:( YTKBaseRequest *)request{
    NSString * info = @"";
    if (request && request.error) {
        if (request.error.code==NSURLErrorNotConnectedToInternet) {
            info = @"请检查网络!";
        }else if (request.error.code==NSURLErrorTimedOut) {
            info = @"请求超时,请重试!";
        }else if (request.responseStatusCode == 401) {
            info = @"401";
        }else if (request.responseStatusCode == 403) {
            info = @"403";
        }else if (request.responseStatusCode == 404) {
            info = @"404";
        }else if (request.responseStatusCode == 500) {
            info = @"服务器报错,请稍后再试!";
        }else
        {
            info = @"网络异常,请重试!";
        }
    }
    return info;
}
 
@end
